{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "4658d71a",
      "metadata": {
        "id": "4658d71a"
      },
      "source": [
        "# Conversation Agent (for Chat Models)\n",
        "\n",
        "This notebook walks through using an agent optimized for conversation, using ChatModels. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may want the agent to be able to chat with the user as well.\n",
        "\n",
        "This is accomplished with a specific type of agent (`chat-conversational-react-description`) which expects to be used with a memory component."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install langchain\n",
        "!pip install google-search-results\n",
        "!pip install openai"
      ],
      "metadata": {
        "id": "efpRpEwvNXU5"
      },
      "id": "efpRpEwvNXU5",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "f65308ab",
      "metadata": {
        "id": "f65308ab"
      },
      "outputs": [],
      "source": [
        "from langchain.agents import Tool\n",
        "from langchain.memory import ConversationBufferMemory\n",
        "from langchain.chat_models import ChatOpenAI\n",
        "from langchain.utilities import SerpAPIWrapper\n",
        "from langchain.agents import initialize_agent\n",
        "from langchain.agents import AgentType\n",
        "from getpass import getpass"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "SERPAPI_API_KEY = getpass()"
      ],
      "metadata": {
        "id": "qMOoW5QYNlPQ"
      },
      "id": "qMOoW5QYNlPQ",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "5fb14d6d",
      "metadata": {
        "id": "5fb14d6d"
      },
      "outputs": [],
      "source": [
        "search = SerpAPIWrapper(serpapi_api_key=SERPAPI_API_KEY)\n",
        "tools = [\n",
        "    Tool(\n",
        "        name = \"Current Search\",\n",
        "        func=search.run,\n",
        "        description=\"useful for when you need to answer questions about current events or the current state of the world. the input to this should be a single search term.\"\n",
        "    ),\n",
        "]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "dddc34c4",
      "metadata": {
        "id": "dddc34c4"
      },
      "outputs": [],
      "source": [
        "memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "OPENAI_API_KEY = getpass()"
      ],
      "metadata": {
        "id": "pJWcpWnoN56_"
      },
      "id": "pJWcpWnoN56_",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "cafe9bc1",
      "metadata": {
        "id": "cafe9bc1"
      },
      "outputs": [],
      "source": [
        "llm=ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0)\n",
        "agent_chain = initialize_agent(tools, llm, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "dc70b454",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 192
        },
        "id": "dc70b454",
        "outputId": "9e3d6857-72de-472f-b531-9a7b843f1621"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3m{\n",
            "    \"action\": \"Final Answer\",\n",
            "    \"action_input\": \"Hello Bob! How can I assist you today?\"\n",
            "}\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Hello Bob! How can I assist you today?'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 8
        }
      ],
      "source": [
        "agent_chain.run(input=\"hi, i am bob\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "3dcf7953",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 192
        },
        "id": "3dcf7953",
        "outputId": "9afdbf2c-ceed-4835-9975-0841dd2162d6"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3m{\n",
            "    \"action\": \"Final Answer\",\n",
            "    \"action_input\": \"Your name is Bob.\"\n",
            "}\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Your name is Bob.'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 9
        }
      ],
      "source": [
        "agent_chain.run(input=\"what's my name?\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "aa05f566",
      "metadata": {
        "scrolled": false,
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 316
        },
        "id": "aa05f566",
        "outputId": "d38fe468-6c94-450a-9f07-0044bf7beb34"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3m{\n",
            "    \"action\": \"Current Search\",\n",
            "    \"action_input\": \"Thai food dinner recipes\"\n",
            "}\u001b[0m\n",
            "Observation: \u001b[36;1m\u001b[1;3m64 easy Thai recipes for any night of the week · Thai curry noodle soup · Thai yellow cauliflower, snake bean and tofu curry · Thai-spiced chicken hand pies · Thai ...\u001b[0m\n",
            "Thought:\u001b[32;1m\u001b[1;3m{\n",
            "    \"action\": \"Final Answer\",\n",
            "    \"action_input\": \"Here are some Thai food dinner recipes you can try this week: Thai curry noodle soup, Thai yellow cauliflower, snake bean and tofu curry, Thai-spiced chicken hand pies, and many more. You can find the full list of recipes at the source I found earlier.\"\n",
            "}\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Here are some Thai food dinner recipes you can try this week: Thai curry noodle soup, Thai yellow cauliflower, snake bean and tofu curry, Thai-spiced chicken hand pies, and many more. You can find the full list of recipes at the source I found earlier.'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 10
        }
      ],
      "source": [
        "agent_chain.run(\"what are some good dinners to make this week, if i like thai food?\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "c5d8b7ea",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 192
        },
        "id": "c5d8b7ea",
        "outputId": "105db01e-c0f7-4b82-edd9-ea02a02fc66a"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3m{\n",
            "    \"action\": \"Final Answer\",\n",
            "    \"action_input\": \"The last letter in your name is 'b'. Argentina won the World Cup in 1978.\"\n",
            "}\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "\"The last letter in your name is 'b'. Argentina won the World Cup in 1978.\""
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 11
        }
      ],
      "source": [
        "agent_chain.run(input=\"tell me the last letter in my name, and also tell me who won the world cup in 1978?\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "f608889b",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 278
        },
        "id": "f608889b",
        "outputId": "49ea0e17-d8cd-4de9-e119-e6006caea32f"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3m{\n",
            "    \"action\": \"Current Search\",\n",
            "    \"action_input\": \"weather in pomfret\"\n",
            "}\u001b[0m\n",
            "Observation: \u001b[36;1m\u001b[1;3mCloudy with showers. Low around 55F. Winds S at 5 to 10 mph. Chance of rain 60%. Humidity76%.\u001b[0m\n",
            "Thought:\u001b[32;1m\u001b[1;3m{\n",
            "    \"action\": \"Final Answer\",\n",
            "    \"action_input\": \"Cloudy with showers. Low around 55F. Winds S at 5 to 10 mph. Chance of rain 60%. Humidity76%.\"\n",
            "}\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Cloudy with showers. Low around 55F. Winds S at 5 to 10 mph. Chance of rain 60%. Humidity76%.'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 12
        }
      ],
      "source": [
        "agent_chain.run(input=\"whats the weather like in pomfret?\")"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.1"
    },
    "colab": {
      "provenance": []
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
